package com.lizhenhua.timeoutcancel.service;


import com.github.wxpay.sdk.WXPay;
import com.lizhenhua.fmmall.entity.Orders;
import com.lizhenhua.timeoutcancel.feignClient.OrderCloseFeignClient;
import com.lizhenhua.timeoutcancel.feignClient.OrderTimeoutQueryClient;
import com.lizhenhua.timeoutcancel.feignClient.UpdateOrderStatusFeignClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import tk.mybatis.mapper.entity.Example;


import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class OrderTimeOutCancelJob {
    @Autowired
    private OrderTimeoutQueryClient orderTimeoutQueryClient;

    @Autowired
    private UpdateOrderStatusFeignClient updateOrderStatusFeignClient;
    WXPay wxPay = new WXPay(new MyPayConfig());


    @Autowired
    private OrderCloseFeignClient orderCloseFeignClient;

    //    @Scheduled(cron = "0/60 * * * * ?")
    public void checkAmdCloseOrder() {
        System.out.println("----------------------------hello world");

        try {
            //1. 查询超过三十分钟 订单状态依然为待支付 状态的订单  调用orderTimeoutQuery
            List<Orders> orders = orderTimeoutQueryClient.query();
            //2 先访问微信平台接口， 确认当前最终的支付状态
            for (Orders o : orders
            ) {

                HashMap<String, String> hashMap = new HashMap<>();
                // 拿着每个订单的id 查询状态
                hashMap.put("out_trade_no", o.getOrderId());

                Map<String, String> resp = wxPay.orderQuery(hashMap);
                //2.1如果确实未支付则取消订单  如果已支付呢则修改当前状态为 代发货/已支付 status2
                if ("SUCCESS".equalsIgnoreCase(resp.get("trade_state"))) {
                    Orders orders1 = new Orders();
                    orders1.setOrderId(o.getOrderId());
                    orders1.setStatus("2");
                    // 修改指定字段的内容
                    int i = updateOrderStatusFeignClient.update(orders1);
                } else if ("NOTPAY".equalsIgnoreCase(resp.get("trade_state"))) {

                    //2.2 如果确实未支付 则取消订单
                    // a.向微信支付平台发送请求，关闭当前支付链接
                    // 关闭订单
                    // 需要的参数  商户id 和订单号

                    Map<String, String> closeMap = wxPay.closeOrder(hashMap);
                    // {nonce_str=jOemGAZkxVOoNbt6, appid=wx632c8f211f8122c6, sign=701D95A115464A7C493F7F163A10D190, return_msg=OK, result_code=SUCCESS, mch_id=1497984412, return_code=SUCCESS} 返回的值

                    if ("SUCCESS".equalsIgnoreCase(closeMap.get("result_code"))) {
                        orderCloseFeignClient.closeOrder(o.getOrderId(), 1);
                    }

                }
            }
        } catch (Exception e) {

            System.out.println("定时关闭订单出现异常");
        }


    }

}
